//
//  YWTroubleRecordsDetailTableViewController.m
//  maintain
//
//  Created by Kyo on 16/8/23.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWTroubleRecordsDetailTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWConst.h"
#import "YWMacro.h"
#import "YWCommonTool.h"

#import "YWCirculationInfo.h"
#import "YWCirculationManager.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWMissionManager.h"
#import "YWEquipmentFieldRecord.h"
#import "YWEquipmentType.h"

#import "YWPostTroubleBillCell.h"
#import "YWTroubleMissionFinishBillCell.h"
#import "YWTempTroubleFinishBillCell.h"
#import "YWTroubleMutableBIllCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

@interface YWTroubleRecordsDetailTableViewController ()<YWPostTroubleBillCellDelegate>{
    BOOL showTopLine;
    BOOL showBottomLine;
    UIWebView *phoneCallWebView;
}
@property (nonatomic, strong) NSMutableArray* dataSource;
@property (nonatomic, strong) NSArray *circulationsArray;
@property (nonatomic, copy) NSString *fieldRecordContent;

@property (nonatomic, strong) UILabel *tableHeadLabel;
@end

@implementation YWTroubleRecordsDetailTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"故障详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self.tableView registerClass:[YWPostTroubleBillCell class] forCellReuseIdentifier:YWPostTroubleBillCellIdentifier];
    [self.tableView registerClass:[YWTroubleMissionFinishBillCell class] forCellReuseIdentifier:YWTroubleMissionFinishBillCellIdentifier];
    [self.tableView registerClass:[YWTempTroubleFinishBillCell class] forCellReuseIdentifier:YWTempTroubleFinishBillCellIdentifier];
    [self.tableView registerClass:[YWTroubleMutableBIllCell class] forCellReuseIdentifier:YWTroubleMutableBIllCellIdentifier];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.tableHeaderView = self.tableHeadLabel;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, KbottomViewH)];
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (self.troubleRecord.missionId>0) {
        [self refreshTop];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshTop
{
    [[YWCirculationManager shareManager] requestCirculationInfoWithTroubleId:self.troubleRecord.missionId needTip:YES WithComplete:^(BOOL success) {
        if (success) {
            _dataSource = nil;
            [self setupHeadLabel:_tableHeadLabel];
            [self.tableView reloadData];
        }
    }];
}

- (NSMutableArray*)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        if (self.troubleRecord) {
            NSMutableArray *firstArray = [NSMutableArray array];
            [firstArray addObject:self.troubleRecord];
            if (self.troubleRecord.missionId>0) {
                [firstArray addObject:self.troubleRecord];
            }
            [_dataSource addObject:firstArray];
        }
        //流转
        _circulationsArray = self.troubleRecord.missionId >0 ? [[YWCirculationManager shareManager] circulationInfoArrayWithTroubleId:self.troubleRecord.missionId] : nil;
        if (_circulationsArray.count) {
            [_dataSource addObject:_circulationsArray];
        }
        
        [self setUpDataSource];
    }
    
    return _dataSource;
    
}

- (void)setUpDataSource{
    __block NSUInteger isLastAssignIdx = 0;
    [_circulationsArray enumerateObjectsUsingBlock:^(YWCirculationInfo*  _Nonnull circulationInfo, NSUInteger idx, BOOL * _Nonnull stop) {
        if (circulationInfo.type == YWCirculationInfoTypeAssignTroubleMission){
            isLastAssignIdx = idx;
            *stop = YES;
        }
    }];
    if (_circulationsArray.count) {
        YWCirculationInfo *circulationInfo = isLastAssignIdx>0?_circulationsArray[isLastAssignIdx]:nil;
        circulationInfo.isLastAssignBill = circulationInfo?YES:NO;
    }
}

- (NSString *)fieldRecordContent{
    if (!_fieldRecordContent) {
        //设备参数
        NSArray *fieldRecordArray = _troubleRecord.equipmentFieldRecord;
        if (fieldRecordArray.count == 0) {
            fieldRecordArray = [[YWMissionManager shareManager] equipmentFieldRecordsWithUniqueTag:_troubleRecord.uniqueTag maintenanceTypeId:YWMaintenanceTypeTrouble];
        }
        
        NSMutableString *contenStr = [NSMutableString string];
        if (fieldRecordArray.count) {
            __block NSString *str = nil;
            [fieldRecordArray enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord*  _Nonnull fieldrecord, NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx != 0) {
                    [contenStr appendString:@"\n"];
                }
                if (fieldrecord.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldOption.fieldOptionText?:@"未填写"];
                }else{
                    str = [NSString stringWithFormat:@"%@: %@",fieldrecord.fieldName,fieldrecord.fieldValue?:@"未填写"];
                }
                [contenStr appendString:str];
            }];
        }else{
            [contenStr appendString:@"无"];
        }
        _fieldRecordContent = [NSString stringWithFormat:@"%@",contenStr];
    }
    return _fieldRecordContent;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionCount = self.dataSource[section];
    return sectionCount.count;
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return section==0 ? 0.01f : 10.0f;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0 && self.troubleRecord.missionId>0) {
            YWPostTroubleBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWPostTroubleBillCellIdentifier];
            [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
            return cell;
        }else {
            if (self.troubleRecord.missionId>0) {
                YWTroubleMissionFinishBillCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier];
                [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
                return cell;
            }else{
                YWTempTroubleFinishBillCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTempTroubleFinishBillCellIdentifier];
                [self configureTempTroubleFinishBillCell:cell atIndexPath:indexPath];
                return cell;
            }
        }
    } else if (indexPath.section == 1) {
        YWTroubleMutableBIllCell* cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMutableBIllCellIdentifier];
        //        上下线的显示
        NSArray *rowArray = self.dataSource[indexPath.section];
        cell.isFirstRow = NO;
        if (indexPath.row == 0) {
            showTopLine = NO;
            showBottomLine = YES;
            cell.isFirstRow = YES;
        } else if (indexPath.row == (rowArray.count - 1)){
            showTopLine = YES;
            showBottomLine = NO;
        } else {
            showTopLine = YES;
            showBottomLine = YES;
        }
        UIView *topLine = (UILabel *)[cell viewWithTag:KTopLineTag];
        UIView *bottomLine = (UILabel *)[cell viewWithTag:KBottomLineTag];
        topLine.hidden = !showTopLine;
        bottomLine.hidden = !showBottomLine;
        //        cell赋值
        [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
        return cell;
    }
    return [[UITableViewCell alloc] init];
}
#pragma configure cell
- (void)configurePostTroubleBillCell:(YWPostTroubleBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.delegate = self;
    cell.troubleRecord = self.troubleRecord;
}

- (void)configureTroubleFinishBillCell:(YWTroubleMissionFinishBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.troubleRecord = self.troubleRecord;
    cell.fieldRecordContent = self.fieldRecordContent;
}

- (void)configureTempTroubleFinishBillCell:(YWTempTroubleFinishBillCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.troubleRecord = self.troubleRecord;
    cell.fieldRecordContent = self.fieldRecordContent;
}

- (void)configureTroubleMutableBIllCell:(YWTroubleMutableBIllCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWCirculationInfo *circulationInfoc = self.dataSource[indexPath.section][indexPath.row];
    //cell.troubleMission = self.troubleMission;
    cell.circulationInfo = circulationInfoc;
}

#pragma mark - UITableViewDataDelegate mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section == 0) {
//        if (indexPath.row == 0 && self.troubleRecord.missionId>0) {
//            return [tableView fd_heightForCellWithIdentifier:YWPostTroubleBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWPostTroubleBillCell *cell) {
//                [self configurePostTroubleBillCell:cell atIndexPath:indexPath];
//            }];
//        }else {
//            if (self.troubleRecord.missionId>0) {
//                return [tableView fd_heightForCellWithIdentifier:YWTroubleMissionFinishBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMissionFinishBillCell *cell) {
//                    [self configureTroubleFinishBillCell:cell atIndexPath:indexPath];
//                }];
//            }else{
//                return [tableView fd_heightForCellWithIdentifier:YWTempTroubleFinishBillCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTempTroubleFinishBillCell *cell) {
//                    [self configureTempTroubleFinishBillCell:cell atIndexPath:indexPath];
//                }];
//            }
//            
//        }
//    } else if (indexPath.section == 1) {
//        return [tableView fd_heightForCellWithIdentifier:YWTroubleMutableBIllCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMutableBIllCell *cell) {
//            [self configureTroubleMutableBIllCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return 0.0;
//    }
//    return 0.0;
//}

-(UILabel *)tableHeadLabel{
    if (!_tableHeadLabel) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.font = KTitleFont;
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        _tableHeadLabel = label;
        [self setupHeadLabel:_tableHeadLabel];
    }
    return _tableHeadLabel;
}

- (void)setupHeadLabel:(UILabel*)label{
    NSString *sequence = _troubleRecord.recordSequence?:@"无";//troubleMission.troubleSequence?:@"无";
    label.attributedText = [YWCommonTool labelAttributedStringWithFristStr:@"编号: " secondStr:sequence secondColor:[UIColor customYellowColor]];
}

- (void)clickPostTroubleMobileWithNumber:(NSString *)mobileNumber{
    if (mobileNumber.length) {
        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",mobileNumber]];
        if ( !phoneCallWebView ) {
            phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];// 这个webView只是一个后台的 不需要add到页面上来  效果跟方法二一样 但是这个方法是合法的
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
        });
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有此联系人的电话号码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
@end
